package pCloud.client;

import pCloud.crypto.kpabe.KPAbe;
import pCloud.crypto.kpabe.TransformedCipherMessage;
import pCloud.crypto.kpabe.UKMessage;

public class DataUserCryptoHandle {

	KPAbe crypto;
	int alpha, windowIndex, beta;
	long lastArrivalTime, arrivalTime;

	public DataUserCryptoHandle() {
		this.crypto = new KPAbe();
		lastArrivalTime = 0;
	}

	// on receipt of UKMessage from owner, initilize crypto
	public void initialize(UKMessage ukm) {
		long start = System.currentTimeMillis();
		if (ukm.getMask() != null) {
			crypto.initUser_slidingWindow(ukm.getPubKey(),
					ukm.getTransformKey(), ukm.getKey(), ukm.getMask(),
					ukm.getBeta());
			this.alpha = ukm.getAlpha();
			this.beta = ukm.getBeta();
		} else {
			crypto.initUser_simple(ukm.getPubKey(), ukm.getTransformKey(),
					ukm.getKey());
		}
		long end = System.currentTimeMillis();
		System.out.println("data user setup: " + (end - start));
	}

	public void decrypt(TransformedCipherMessage tcm) {
		int val;
		if (this.lastArrivalTime == 0)
			this.lastArrivalTime = System.currentTimeMillis();
		long decStart = System.currentTimeMillis();
		if (!tcm.isSlidingWindow()) {
			val = crypto.decrypt_simple(tcm.getCipher(), tcm.getEp());
			System.out.println("received value: " + val);
		} else {
			if (tcm.getIndex() < this.alpha) {
				this.lastArrivalTime = System.currentTimeMillis();
				return;
				// System.out.println("Skipping ...");
			} else {
				this.windowIndex = (tcm.getIndex() - this.alpha) / this.beta;
				val = crypto.decrypt_slidingWindow(tcm.getCipher(),
						tcm.getEp(), this.windowIndex);
				System.out.println("received value: " + val);
			}
		}
		this.arrivalTime = System.currentTimeMillis();
		System.out.println("decryption time = "+(this.arrivalTime-decStart));
		System.out.println("inter arrival time = "
				+ (this.arrivalTime - this.lastArrivalTime));
		this.lastArrivalTime = this.arrivalTime;
	}

}
